package cn.zxcoder.controller.pay;

import cn.zxcoder.Tools.ToolUtil;
import cn.zxcoder.entity.Res;
import cn.zxcoder.entity.SystemManage.Dept;
import cn.zxcoder.entity.goods.Product;
import cn.zxcoder.entity.pay.*;
import cn.zxcoder.service.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zx
 * @since 2023-05-10
 */
@RestController
@RequestMapping("/api/Order")
public class OrderController {

    @Autowired
    ICnfService iCnfServiceIml;
    @Autowired
    IModeService iModeServiceIml;
    @Autowired
    IDeptService iDeptServiceIml;
    @Autowired
    IOrderService iOrderServiceIml;
    @Autowired
    IStatService iStatServiceIml;
    @Autowired
    ICnfInfoService iCnfInfoServiceIml;
    @Autowired
    IProductService iProductServiceIml;

    @ApiOperation("获取订单状态")
    @GetMapping("/stat")
    public Res getStat() {
        List<Stat> list = iStatServiceIml.list();
        return new Res(true, JSON.toJSONString(list), "成功获取所有订单状态选项");
    }


    @ApiOperation("获取所有交易订单数据")
    @PostMapping("/list")
    public Res getCnf(@RequestParam String page, @RequestParam String limit, @RequestParam String tnumber,
                      @RequestParam String orderId, @RequestParam String dealId, @RequestParam String mode, @RequestParam String stat) throws Exception {
        Page<Order> ipage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.select(Order.class, info -> !info.getColumn().equals("mode") && !info.getColumn().equals("status") &&
                !info.getColumn().equals("editTime") && !info.getColumn().equals("editUser") && !info.getColumn().equals("tnumber") &&
                !info.getColumn().equals("configId") && !info.getColumn().equals("name") && !info.getColumn().equals("subName"));

        if (!orderId.equals("")) {
            wrapper.like("order_id", orderId);
        }
        if (!dealId.equals("")) {
            wrapper.like("deal_num", dealId);
        }
        if (!stat.equals("")) {
            wrapper.eq("stat_id", Integer.parseInt(stat));
        }
        //查出没有cnfInfo属性的order数据并填充 --->cnfInfo属性（tnumber、mode、name）
        Page<Order> orderPage = iOrderServiceIml.page(ipage, wrapper);
        if (orderPage.getRecords().size() == 0) {
            return new Res(false, null, "不好意思，没有符合您要求的订单数据哦");
        }

        //查询部门信息
        List<Dept> deptList = iDeptServiceIml.list();
        //查询商品信息并填充
        List<Product> productList = iProductServiceIml.list();
        //查询支付配置
        QueryWrapper<Cnf> cnfQueryWrapper = new QueryWrapper<>();
        cnfQueryWrapper.select(Cnf.class, info -> !info.getColumn().equals("name") && !info.getColumn().equals("subName"));
        List<Cnf> cnfList = iCnfServiceIml.list(cnfQueryWrapper);
        //查询订单状态信息
        List<Stat> statList = iStatServiceIml.list();

        //根据上面的填充信息进行属性填充
//        AtomicInteger num = new AtomicInteger();
        orderPage.getRecords().forEach(order -> {
            try {
                //先获取此order对应的各种外键指引的对象
                Dept deptRecord = ToolUtil.getRecord(deptList, Dept.class, order.getDeptId());//对应的Dept对象
                Product productRecord = ToolUtil.getRecord(productList, Product.class, order.getProductId());//对应的product对象
                Cnf cnfRecord = ToolUtil.getRecord(cnfList, Cnf.class, order.getCnfId());//对应的Cnf对象
                Stat statRecord = ToolUtil.getRecord(statList, Stat.class, order.getStatId());//对应的Stat对象
//                if (deptRecord == null||productRecord==null||cnfRecord==null||statRecord==null) {
//                    num.getAndIncrement();
//                    return;
//                }
                //再根据外键对象进行填充
                assert deptRecord != null;
                order.setDeptName(deptRecord.getName());//部门名称
                assert productRecord != null;
                order.setGoodsPrice(productRecord.getGoodsPrice());//商品价格
                order.setGoodsName(productRecord.getGoodsName());//商品名称
                order.setPayAmount(order.getDealMode().equals("退款") ?"-"+productRecord.getGoodsPrice() : productRecord.getGoodsPrice());//支付金额
                assert cnfRecord != null;
                order.setSecertKey(cnfRecord.getSecretKey());//商户签名秘钥
                order.setMerchantCode(cnfRecord.getMerchantCode());//商户号
                order.setSubCode(cnfRecord.getSubCode());//子商户号
                order.setMerchantName(cnfRecord.getMerchantName());//卖家名称
                assert statRecord != null;
                order.setStatName(statRecord.getName());//交易状态名称
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
//        if (num.get() == orderPage.getRecords().size()) {//没有合适的数据
//            return new Res(true, null, "不好意思，没有符合您要求的订单数据哦");
//        }


       //开始填充cnfInfo部分的属性

        QueryWrapper<CnfInfo> cnfInfoQueryWrapper = new QueryWrapper<>();
        if (!tnumber.equals("")) {
            cnfInfoQueryWrapper.like("tnumber", tnumber);
        }
        if (!mode.equals("")) {
            cnfInfoQueryWrapper.eq("mode", mode);
        }
        cnfInfoQueryWrapper.select(CnfInfo.class, info -> !info.getColumn().equals("name") && !info.getColumn().equals("subName"));
        List<CnfInfo> cnfInfoList = iCnfInfoServiceIml.list(cnfInfoQueryWrapper);
        if (cnfInfoList == null) {//这两个条件下的数据没有
            return new Res(false, null, "不好意思，没有符合您要求的订单数据哦");
        }
        int count = 0;
        for (Order order : orderPage.getRecords()) {
            CnfInfo cnfInfo = ToolUtil.getRecord(cnfInfoList, CnfInfo.class, order.getCnfinfoId());
            if (cnfInfo == null) {
                count++;
                continue;
            }
            order.setTnumber(cnfInfo.getTnumber());
            //查询相应的mode对应的name
            Mode mode1 = iModeServiceIml.getById(cnfInfo.getMode());
            order.setName(mode1.getName());
        }
        if (count == orderPage.getRecords().size()) {//假如跟本就没有合适的数据
            return new Res(false, null, "不好意思，没有符合您要求的订单数据哦");
        }
        String result = JSON.toJSONString(orderPage);
        return new Res(true, result, "查询交易订单信息成功");



    }@ApiOperation("保存交易订单")
    @PostMapping("/save")
    public Res saveOrder(@RequestParam String deptId,@RequestParam String tnumber,@RequestParam String productId,
                           @RequestParam String orderId,@RequestParam String dealMode,@RequestParam String remark,
                          @RequestParam String merchantCode, @RequestParam String dealId, @RequestParam String stat) {

        Order order = new Order();
        order.setDeptId(Integer.parseInt(deptId));
        order.setProductId(Integer.parseInt(productId));
        order.setOrderId(orderId);
        order.setDealMode(dealMode);
        order.setDealId(dealId);
        order.setStatId(Integer.parseInt(stat));
        order.setRemark(remark);
        order.setAddTime(new Date());


        //找出cnfinfo_id
        QueryWrapper<CnfInfo> cnfInfoQueryWrapper = new QueryWrapper<>();
        cnfInfoQueryWrapper.eq("tnumber", tnumber);
        cnfInfoQueryWrapper.select(CnfInfo.class, info -> !info.getColumn().equals("name") && !info.getColumn().equals("subName"));
        CnfInfo cnfInfo = iCnfInfoServiceIml.getOne(cnfInfoQueryWrapper);
        Integer cnfInfoId = cnfInfo.getId();

        //找出cnf_id
        QueryWrapper<Cnf> cnfQueryWrapper = new QueryWrapper<>();
        cnfQueryWrapper.eq("merchant_code", merchantCode);
        cnfQueryWrapper.select(Cnf.class, info -> !info.getColumn().equals("name") && !info.getColumn().equals("subName"));
        Cnf cnf = iCnfServiceIml.getOne(cnfQueryWrapper);
        Integer cnfId = cnf.getId();

        //设置这两个id值
        order.setCnfinfoId(cnfInfoId);
        order.setCnfId(cnfId);

        boolean save = iOrderServiceIml.save(order);
        return new Res(save, null, save ? "保存交易订单成功" : "保存交易订单失败");
    }

    @ApiOperation("退款此订单")
    @PostMapping("/refund")
    public Res saveCnf(@RequestParam String id, @RequestParam String orderId) {
        System.out.println(String.format("这里对%s进行退款操作", orderId));
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", Integer.parseInt(id));
        wrapper.set("deal_mode", "退款");
        boolean update = iOrderServiceIml.update(wrapper);
        return new Res(update, null, "退款成功");

    }


    @ApiOperation("删除此订单")
    @DeleteMapping("/delete/{id}")
    public Res deleteCnf(@PathVariable String id) {
        boolean b = iOrderServiceIml.removeById(Integer.parseInt(id));
        return new Res(b, null, b ? "删除此交易订单成功" : "删除此交易订单失败");
    }

    @ApiOperation("通过商品编号获取支付金额、商品价格和商品名称")
    @GetMapping("/goods/{productId}")
    public Res getGoods(@PathVariable String productId) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("id",productId);
        Product res = iProductServiceIml.getOne(wrapper);
        return new Res(res!=null, JSON.toJSONString(res), res==null?"获取指定商品信息失败":"获取指定商品信息成功");


    }

    @ApiOperation("部门编号获得部门名称")
    @GetMapping("/dept/{deptId}")
    public Res getDept(@PathVariable String deptId) {
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        wrapper.eq("id",deptId);
        Dept res = iDeptServiceIml.getOne(wrapper);
        return new Res(res!=null, JSON.toJSONString(res), res==null?"获取指定部门名称失败":"获取指定部门名称成功");


    }

    @ApiOperation("终端编号获取支付方式、子支付方式")
    @GetMapping("/cnfinfo/{tnumber}")
    public Res getCnfInfo(@PathVariable String tnumber) {
        QueryWrapper<CnfInfo> wrapper = new QueryWrapper<>();
        wrapper.select(CnfInfo.class, info -> !info.getColumn().equals("name") && !info.getColumn().equals("subName"));

        wrapper.eq("tnumber",tnumber);
        CnfInfo res = iCnfInfoServiceIml.getOne(wrapper);
        if (res == null) {
            return new Res(false, JSON.toJSONString(res), "获取指定支付配置信息失败");
        }
        //填充属性
        Mode mode = iModeServiceIml.getById(res.getMode());
        res.setName(mode.getName());
        res.setSubname(mode.getSubname());

        return new Res(true, JSON.toJSONString(res), "获取指定支付配置信息成功");
    }

    @ApiOperation("通过商户号获取子商户号、商户卖家、加密类型、商户签名秘钥")
    @GetMapping("/cnf/{merchantCode}")
    public Res getCnf(@PathVariable String merchantCode) {
        QueryWrapper<Cnf> wrapper = new QueryWrapper<>();
        wrapper.select(Cnf.class, info -> !info.getColumn().equals("name") && !info.getColumn().equals("subName"));
        wrapper.eq("merchant_code",merchantCode);
        Cnf res = iCnfServiceIml.getOne(wrapper);
        return new Res(res!=null, JSON.toJSONString(res), res==null?"获取支付配置失败":"获取指定支付配置成功");
    }



}
